//
//  HJChatRoomVC.m
//  project
//
//  Created by hu on 2019/3/25.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJChatRoomVC.h"
#import "HJChatLeftMsgCell.h"
#import "HJChatRightMsgCell.h"
#import "HJPhotoOrVideoRightMsgCell.h"
#import "HJPhotoOrVideoLeftMsgCell.h"
#import "HJGiftCell.h"
#import "HJZuduiCell.h"
#import "HJRefuseCell.h"
#import "HJVoiceLeftCell.h"
#import "HJVoiceRightCell.h"
#import "HJInviteJourneyLeftCell.h"
#import "HJInviteJourneyRightCell.h"
#import "HJGitView.h"
#import "YFCamera.h"
#import "HJSimpleMessage.h"
#import "HJChatTextMsgModel.h"
#import <AVFoundation/AVFoundation.h>
#import "HJVocie.h"
#import "HJVociePlayer.h"
#import "HJTeamVC.h"
#import "YBImageBrowser.h"
#import "LEEAlert.h"
#import "HJInfoDetailVC.h"// 他人资料
#import "YFJourneyModel.h"
#import "HJReportVC.h"// 匿名举报
#import "HJJourneyView.h" // 行程头部视图
#import "YFLikeModel.h"
#import "YFJourneyModel.h"

@interface HJChatRoomVC()<UITextViewDelegate,UITableViewDelegate,UITableViewDataSource,RCIMClientReceiveMessageDelegate,VociePlayerDelegate,LGAudioPlayerDelegate,VociePlayerLeftDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
/*
 * 聊天底部视图
 */
@property (weak, nonatomic) IBOutlet UIView *btmView;
/*
 * 左边话筒
 */
@property (weak, nonatomic) IBOutlet UIButton *vocieBtn;
/*
 * 聊天框
 */
@property (weak, nonatomic) IBOutlet UITextView *inputTextView;
/*
 * 聊天发送按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *senBtn;
/*
 * 聊天框底部分类按钮视图
 */
@property (weak, nonatomic) IBOutlet UIView *btmCategoryView;
/*
 * 聊天框底部位置
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btmView_bottom;
/*
 * 聊天框底部分类按钮视图高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btmCategoryView_H;
/*
 * 底部聊天框视图高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btmView_h;

/*
 * 切换按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *chageBtn;
/*
 * 按住说话
 */
@property (weak, nonatomic) IBOutlet UIButton *vocieNumBtn;

/**
 行程按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *journeyBtn;
@property (nonatomic,strong) NSString * recordFilePath;
@property (nonatomic,strong) AVAudioRecorder * recorder; //录音器



/**
 倒计时计数
 */
@property (nonatomic,assign) NSInteger countDown;
/**
 录音定时器
 */
@property (nonatomic,strong) NSTimer * recordTimer;
/*
 * 是否是最底部
 */
@property (nonatomic,assign) BOOL isScrollBottom;

/**
 行程头部视图
 */
@property (nonatomic,strong, nonnull) HJJourneyView * journeyHeaderView;

/*
 * 礼物视图
 */
@property (nonatomic,strong,nonnull) HJGiftScrollView * giftScrollView;

@property (nonatomic,strong,nonnull) NSMutableArray <RCMessage *>* chatRoomDataArray;

/**
加载gif
 */
@property (nonatomic,strong,nonnull) HJGifImageView * gifImageView;
@property (nonatomic,strong,nonnull) UIView * gifBackView;

/**
 取消语音图片
 */
@property (nonatomic,strong,nonnull) UIImageView * cancelVocieImageView;
/**
 录音
 */
@property (nonatomic,strong,nonnull) HJVocie * vocie;

/**
 自己的行程
 */
@property (nonatomic,strong,nonnull) YFTripModel * journeyModel;
/**
 对方的行程
 */
@property (nonatomic,strong,nonnull) YFTripModel * otherModel;
/**
 对方的信息
 */
@property (nonatomic, strong) YFUserModel *userModel;
@end

static NSString * const journey = @"JourneyCell";
static NSString * const chatLeftMsg = @"ChatLeftMsgCell";
static NSString * const chatRightMsg = @"ChatRightMsgCell";
static NSString * const photoOrVideoRightMsg = @"PhotoOrVideoRightMsgCell";
static NSString * const photoOrVideoLeftMsg = @"PhotoOrVideoLeftMsgCell";
static NSString * const gift = @"GiftCell";
static NSString * const zudui = @"ZuduiCell";
static NSString * const leftVocie = @"VoiceLeftCell";
static NSString * const rightVocie = @"VoiceRightCell";
static NSString * const leftJourneyCell = @"InviteJourneyLeftCell";
static NSString * const rightJourneyCell = @"InviteJourneyRightCell";
static NSString * const RefuseCell = @"RefuseCell";

@implementation HJChatRoomVC


-(void)viewDidLoad {
    [super viewDidLoad];
    self.rightNavImageName = @"more";
    self.navTitle = self.conversationModel.conversationTitle;
    self.countDown = 60;
    self.inputTextView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
    self.inputTextView.layoutManager.allowsNonContiguousLayout = NO;
    [self setupViews];
    [mNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [mNotificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//    NSLog(@"targetId=%@",self.conversationModel.targetId);
    //获取用户信息
    NSString * url = [Api stringByAppendingString:QueryByIdApi];
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    dic[@"userId"] = self.conversationModel.targetId;
    [HJHttpTool get:url params:dic success:^(HJResponeds *result) {
        
        YFUserModel * userModel = [YFUserModel yy_modelWithDictionary:result.data];
        HJInfoDetailVC * infoDetailVC= [HJInfoDetailVC new];
        infoDetailVC.userModel = userModel;
        self.avatarUrl = userModel.avatar;
        [self.tableView reloadData];
    } failure:^(id result) {
    }];
    
    [HJVociePlayer shareManager].delegate = self;
    
    [self.btmCategoryView setHidden:YES];
  
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //键盘设置
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    [manager setEnable:NO];
}

//发消息通知消息列表更新
- (void)localLastMessage:(RCMessageContent *)msg {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"localLasteMessage" object:nil userInfo:@{@"msg" : msg, @"userId" : self.conversationModel.targetId}];
}
#pragma mark -- UI
-(void)setupViews {
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    //历史聊天记录
    [self refreshHistoryData];
    //获取聊天室数据
    
    [self reloadChatRoomListWithLastID:-1 targetID:self.conversationModel.targetId];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 10, 0);
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.inputTextView.layer.cornerRadius = 10;
//    self.inputTextView.clipsToBounds = YES;
    [self.vocieNumBtn rounded:UIRectCornerAllCorners radius:20];
    // 设置消息接收监听
    [[RCIMClient sharedRCIMClient] setReceiveMessageDelegate:self object:nil];
    // 注册自定义消息体
    [[RCIMClient sharedRCIMClient] registerMessageType:[HJSimpleMessage class]];
    
    // 头部行程点击事件
    @weakify(self)
    [[self.journeyBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        if ([self.journeyModel isEqual:[NSNull null]]) return;
        self.journeyBtn.hidden = YES;
        [self.journeyHeaderView show];
    }];
    [self loadJourneyRequestData];
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[HJVociePlayer shareManager] stopAudioPlayer];
    //键盘设置
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    [manager setEnable:YES];

}


/**
 懒加载行程视图
 @return journeyHeaderView
 */
-(HJJourneyView *)journeyHeaderView {
    if (!_journeyHeaderView) {
        _journeyHeaderView = [HJJourneyView initJourneyViewWithframe:CGRectMake(10, 5, self.view.bounds.size.width-20, 220)];
        [_journeyHeaderView loadData:self.journeyModel];
        @weakify(self)
        _journeyHeaderView.cancleClick = ^(BOOL isCancle) {
            @strongify(self)
            self.journeyBtn.hidden = !isCancle;
            self.journeyHeaderView = nil;
        };
        [self.view insertSubview:_journeyHeaderView aboveSubview:self.tableView];
    }
    return _journeyHeaderView;
}
#pragma mark -- 行程数据请求
-(void)loadJourneyRequestData {
    NSString * journeyUrl = [Api stringByAppendingString:TripMatchByUserIdApi];
    [HJHttpTool get:journeyUrl params:@{@"userIdA":self.conversationModel.targetId,@"userIdB":[HJUserManager getUserModel].userId} success:^(HJResponeds *result) {
//        LKLog(@"%@",result.data);
        if ([result.data isEqual:[NSNull null]]) return;
        self.otherModel = [YFTripModel yy_modelWithDictionary:result.data[@"likeTrip"]];// 对方的行程
        self.journeyModel = [YFTripModel yy_modelWithDictionary:result.data[@"trip"]];// 自己的行程
    } failure:^(id result) {
        
    }];
}
#pragma mark -- 导航右边按钮点击
-(void)didClickRightNavAction {
    @weakify(self)
    [LEEAlert actionsheet].config
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        @strongify(self);
        action.title = @"查看资料";
        action.titleColor = [UIColor colorWithHex:0x000000];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:14];
        action.clickBlock = ^{
            @weakify(self)
            NSString * url = [Api stringByAppendingString:QueryByIdApi];
            NSMutableDictionary * dic = [NSMutableDictionary dictionary];
            dic[@"userId"] = self.conversationModel.targetId;
            [HJHttpTool get:url params:dic success:^(HJResponeds *result) {
                @strongify(self);
                YFUserModel * userModel = [YFUserModel yy_modelWithDictionary:result.data];
                HJInfoDetailVC * infoDetailVC= [HJInfoDetailVC new];
                infoDetailVC.userModel = userModel;
                [self.navigationController pushViewController:infoDetailVC animated:YES];
            } failure:^(id result) {
            }];
        };
    })
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"匿名举报";
        action.titleColor = [UIColor colorWithHex:0x000000];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:14];
        @strongify(self)
        action.clickBlock = ^{
            HJReportVC * reportVC = [HJReportVC new];
            reportVC.reportUserId = self.conversationModel.targetId;
            [self.navigationController pushViewController:reportVC animated:YES];
        };
    })
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"拉黑";
        action.titleColor = [UIColor colorWithHex:0x000000];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:14];
        @strongify(self)
        action.clickBlock = ^{
            NSString * privacyUrl = [Api stringByAppendingString:PullBlackFriendApi];
            NSMutableDictionary * dic = [NSMutableDictionary dictionary];
            dic[@"blackUserId"] = self.conversationModel.targetId;
            dic[@"userId"] = [HJUserManager getUserModel].userId;
            [HJHttpTool post:privacyUrl params:dic success:^(HJResponeds *result) {
                [self showSuccessHUDWithStr:result.resultDesc];
            } failure:^(id result) {
                [self showErrorHUDWithError:result];
            }];
        };
    })
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.type = LEEActionTypeCancel;
        action.title = @"取消";
        action.titleColor = [UIColor colorWithHex:0x999999];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:14];
    })
    .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
    .LeeShow();
}
#pragma mark -- 上拉加载历史聊天记录
-(void)refreshHistoryData {
    WS(weakSelf)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        RCMessage * message = [weakSelf.chatRoomDataArray firstObject];
        [self reloadChatRoomListWithLastID:message.messageId targetID:weakSelf.conversationModel.targetId];
    }];
}

-(NSMutableArray<RCMessage *> *)chatRoomDataArray {
    if (!_chatRoomDataArray) {
        _chatRoomDataArray = [NSMutableArray array];
    }
    return _chatRoomDataArray;
}
#pragma mark --获取聊天室聊天信息
-(void)reloadChatRoomListWithLastID:(long)lastMsgId targetID:(NSString *)targetID {
    NSArray * historyArr = [[RCIMClient sharedRCIMClient] getHistoryMessages:ConversationType_PRIVATE targetId:targetID oldestMessageId:lastMsgId count:10];
    
    if (lastMsgId == -1 && targetID == self.conversationModel.targetId) {
        NSEnumerator *enumerator = [historyArr reverseObjectEnumerator];
        NSMutableArray *jxArr = (NSMutableArray *)[enumerator allObjects];
        [self.chatRoomDataArray addObjectsFromArray:jxArr];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView endRefresh];
            [self.tableView reloadData];
        });
    }else {
        for (RCMessage * msg in historyArr) {
            [self.chatRoomDataArray insertObject:msg atIndex:0];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView endRefresh];
            [self.tableView reloadData];
        });
        if (historyArr.count>0) {
           [self tableViewScrollToTopWithRowIndex:historyArr.count-1];
        }
    }
}

/**
 拉取历史记录 滚动到历史记录的最后一条后 滑动到顶继续下拉
 @param index cell的row
 */
-(void)tableViewScrollToTopWithRowIndex:(NSInteger)index {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    });
}
/*!
 接收消息的回调方法
 @param message     当前接收到的消息
 @param nLeft       还剩余的未接收的消息数，left>=0
 */
- (void)onReceived:(RCMessage *)message left:(int)nLeft object:(id)object {
    if (![message.targetId isEqualToString:self.conversationModel.targetId]) return;
    [self.chatRoomDataArray addObject:message];
    [mNotificationCenter postNotificationName:NotificationRCReceive object:nil userInfo:@{@"clearMsgTarget":self.conversationModel.targetId}];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self tableViewScroll];
    });
    
}

#pragma mark -- 键盘弹起通知
-(void)keyboardWillShow:(NSNotification *)notification {
    CGRect keyboardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat needY = SCREEN_HEIGTH - Height_TabBar - keyboardFrame.size.height - self.btmView_h.constant;
    CGRect tabFrame = self.tableView.frame;
    tabFrame.size.height = needY;
//修改tableView高度，滚动到底部
    self.tableView.frame = tabFrame;
    [self tableViewScroll];
    self.btmView_bottom.constant = -keyboardFrame.size.height;
    LKLog(@"keyboardWillShow=%@",NSStringFromCGRect(self.btmView.frame));
}
#pragma mark -- 键盘收回通知
-(void)keyboardWillHide:(NSNotification *)notification {
//    CGRect ViewY = self.tableView.frame;
//    CGRect btmFrame = self.btmView.frame;
//    CGFloat needY = ViewY.size.height;
//    btmFrame.origin.y = needY;
//    self.btmView.frame = btmFrame;
    self.chageBtn.hidden = NO;
    self.senBtn.hidden = YES;
    CGRect tabFrame = self.tableView.frame;
    tabFrame.size.height = SCREEN_WIDTH - Height_TabBar;;
    self.btmView_bottom.constant = 0;
    
//    LKLog(@"keyboardWillHide=%@",NSStringFromCGRect(self.btmView.frame));
}


#pragma mark -- UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.chatRoomDataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RCMessage * message = self.chatRoomDataArray[indexPath.row];
    if ([message.content isMemberOfClass:[RCTextMessage class]]) {
        RCTextMessage *testMessage = (RCTextMessage *)message.content;
        if (message.messageDirection == MessageDirection_RECEIVE) {// 接收
            HJChatLeftMsgCell * chatLeftCell = [tableView dequeueReusableCellWithIdentifier:chatLeftMsg];
            [chatLeftCell loadLeftMoreWithData:testMessage];
            return chatLeftCell;
        }else { // 发送
            HJChatRightMsgCell * chatRightCell = [tableView dequeueReusableCellWithIdentifier:chatRightMsg];
            if (message.sentStatus == SentStatus_FAILED) {
                chatRightCell.sendError.hidden = NO;
            }else {
                chatRightCell.sendError.hidden = YES;
            }
            chatRightCell.targetId = self.conversationModel.targetId;
            [chatRightCell loadRightMoreWithData:testMessage];
            
            return chatRightCell;
        }
    }else if ([message.content isMemberOfClass:[RCImageMessage class]] || [message.content isMemberOfClass:[RCSightMessage class]]) {// 视频或者图片
        if (message.messageDirection == MessageDirection_RECEIVE) {// 接收
            HJPhotoOrVideoLeftMsgCell * photoOrVideoLeftCell = [tableView dequeueReusableCellWithIdentifier:photoOrVideoLeftMsg];
            
            //[photoOrVideoLeftCell loadLeftImageOrVideoWitMsg:message];
            [photoOrVideoLeftCell loadLeftImageOrVideoWitMsg:message Avatar:self.avatarUrl];
            @weakify(self)
            photoOrVideoLeftCell.didLeftSelecteImageBrowser = ^(UIImageView * _Nonnull contentImageView) {
                @strongify(self)
                [self didSelecteImageBrowserWithIndex:indexPath.row imageView:contentImageView];
            };
            return photoOrVideoLeftCell;
        }else {
            HJPhotoOrVideoRightMsgCell * photoOrVideoRightCell = [tableView dequeueReusableCellWithIdentifier:photoOrVideoRightMsg];
            [photoOrVideoRightCell loadRightImageOrVideoWitMsg:message];
            photoOrVideoRightCell.targetId = self.conversationModel.targetId;
            @weakify(self)
            photoOrVideoRightCell.didRightSelectImage = ^(UIImageView * _Nonnull contentImageView) {
                @strongify(self)
                [self didSelecteImageBrowserWithIndex:indexPath.row imageView:contentImageView];
            };
            return photoOrVideoRightCell;
        }
    }else if ([message.content isMemberOfClass:[RCVoiceMessage class]]) {// 语音
        if (message.messageDirection == MessageDirection_RECEIVE) {// 接收
            HJVoiceLeftCell * leftVocieCell = [tableView dequeueReusableCellWithIdentifier:leftVocie];
            [leftVocieCell loadLeftVocieMsg:message avatarUrl:self.avatarUrl];
           // [leftVocieCell loadLeftVocieMsg:message];
            leftVocieCell.delegate = self;
            return leftVocieCell;
        }else {
            HJVoiceRightCell * rightVocieCell = [tableView dequeueReusableCellWithIdentifier:rightVocie];
            [rightVocieCell loadRightVocieMsg:message];
            rightVocieCell.targetId = self.conversationModel.targetId;
            rightVocieCell.delegate = self;
            return rightVocieCell;
        }
    }else if ([message.content isMemberOfClass:[HJSimpleMessage class]]) {
        HJSimpleMessage * simpleMsg = (HJSimpleMessage *)message.content;
        HJSimpleModel * simpleModel = [HJSimpleModel yy_modelWithDictionary:simpleMsg.content];
//        LKLog(@"%@,%@",simpleModel.typeCn,simpleModel.data.team.startText);
        if (simpleModel.type.intValue==8) {// 邀请组队
            if (![simpleModel.sendUserId isEqualToString:[HJUserManager getUserModel].userId]) {
                HJInviteJourneyLeftCell * inviteLeftCell = [tableView dequeueReusableCellWithIdentifier:leftJourneyCell];
                [inviteLeftCell loadLeftData:simpleModel];
                @weakify(self)
                inviteLeftCell.leftCellClickedBlock = ^{
                    @strongify(self)
                    [self pushToTeamViewControllerWithUIType:UIContentTypeEdite index:indexPath];
                };
                return inviteLeftCell;
            }else {
                HJInviteJourneyRightCell * inviteRightCell = [tableView dequeueReusableCellWithIdentifier:rightJourneyCell];
                [inviteRightCell loadRightData:simpleModel];
                @weakify(self)
                inviteRightCell.rightCellClickedBlock = ^{
                    @strongify(self)
                    [self pushToTeamViewControllerWithUIType:UIContentTypeMe index:indexPath];
                };
                return inviteRightCell;
            }
        }else if (simpleModel.type.intValue == 9) {// 9修改行程组队
            HJGiftCell * editCell = [tableView dequeueReusableCellWithIdentifier:gift];
            [editCell loadData:simpleModel];
            @weakify(self)
            editCell.editBtnClickedBlock = ^{// 修改后查看
                @strongify(self)
                if (![simpleModel.data.user.userId isEqualToString:[HJUserManager getUserModel].userId]) {
                    [self pushToTeamViewControllerWithUIType:UIContentTypeMe index:indexPath];
                }else {
                    [self pushToTeamViewControllerWithUIType:UIContentTypeEdite index:indexPath];
                }
            };
            return editCell;
        }else if (simpleModel.type.intValue == 10) {// 10 拒绝行程组队
            HJRefuseCell * refuseCell = [tableView dequeueReusableCellWithIdentifier:RefuseCell];
            [refuseCell loadData:simpleModel];
            
            return refuseCell;
        } else if (simpleModel.type.intValue==11) {//同意行程组队
            HJZuduiCell * zuduiCell = [tableView dequeueReusableCellWithIdentifier:zudui];
            @weakify(self)
            zuduiCell.clicked = ^{// 点击查看组队详情
                @strongify(self)
                [self pushToTeamViewControllerWithUIType:UIContentTypeAgree index:indexPath];
            };
            [zuduiCell loadData:simpleModel];
            
            return zuduiCell;
        }
//        LKLog(@"自定义消息：%@",simpleMsg.content);
    }
    return [UITableViewCell new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    RCMessage * message = self.chatRoomDataArray[indexPath.row];
    if ([message.content isMemberOfClass:[RCTextMessage class]]) {
        RCTextMessage *testMessage = (RCTextMessage *)message.content;
        HJChatTextMsgModel * model = [[HJChatTextMsgModel alloc]init];
        model.content = testMessage.content;
//        LKLog(@"testMessage.content=%f",model.cellHeight);
        return model.cellHeight;
    }else if ([message.content isMemberOfClass:[RCImageMessage class]] ||[message.content isMemberOfClass:[RCSightMessage class]]) {
        return 150;
    }else if ([message.content isMemberOfClass:[RCVoiceMessage class]]) {
        return 85;
    }else if ([message.content isMemberOfClass:[HJSimpleMessage class]]) {
        HJSimpleMessage * simpleMsg = (HJSimpleMessage *)message.content;
        HJSimpleModel * simpleModel = [HJSimpleModel yy_modelWithDictionary:simpleMsg.content];
        if (simpleModel.type.intValue == 8) {//邀请组队
            return 120;
        }else if (simpleModel.type.intValue == 9 || simpleModel.type.intValue == 10) {//修改行程组队  拒绝行程组队
            return 45;
        }else if (simpleModel.type.intValue == 11) {//同意行程组队
            return 145;
        }
    }
    return 0.01;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isScrollBottom) {
        return;
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (@available(iOS 11.0, *)) {
                [self.tableView performBatchUpdates:nil completion:nil];
            } else {
                [self.tableView beginUpdates];
                [self.tableView endUpdates];
            }
            [self tableViewScroll];
            self.isScrollBottom = YES;
        });
    }
}
-(void)tableViewScroll {
    if (self.chatRoomDataArray.count>=1) {
         [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatRoomDataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

#pragma mark --点击右边播放语音
-(void)voiceMessageTaped:(HJVoiceRightCell *_Nonnull)cell data:(NSData *_Nonnull)data isRgiht:(BOOL)isRight {
    [cell setVoicePlayState:LGVoicePlayStatePlaying];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [[HJVociePlayer shareManager] playAudioWithURLString:data atIndex:indexPath.row IsRight:isRight];
}
#pragma mark --点击左边播放语音
-(void)voiceLeftMessageTaped:(HJVoiceLeftCell *)cell data:(NSData *)data isRgiht:(BOOL)isRight {
    [cell setVoiceLeftPlayState:LGVoicePlayLeftStatePlaying];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [[HJVociePlayer shareManager] playAudioWithURLString:data atIndex:indexPath.row IsRight:isRight];
}

#pragma mark - LGAudioPlayerDelegate
- (void)audioPlayerStateDidChanged:(LGAudioPlayerState)audioPlayerState forIndex:(NSUInteger)index IsRight:(BOOL)isRight {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    
    if (isRight) {
        HJVoiceRightCell *voiceRightMessageCell = [self.tableView cellForRowAtIndexPath:indexPath];
        LGVoicePlayState voicePlayState;
        switch (audioPlayerState) {
            case LGAudioPlayerStateNormal:
                voicePlayState = LGVoicePlayStateNormal;
                break;
            case LGAudioPlayerStatePlaying:
                voicePlayState = LGVoicePlayStatePlaying;
                break;
            case LGAudioPlayerStateCancel:
                voicePlayState = LGVoicePlayStateCancel;
                break;
            default:
                break;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [voiceRightMessageCell setVoicePlayState:voicePlayState];
        });
    }else {
        HJVoiceLeftCell *voiceLeftMessageCell = [self.tableView cellForRowAtIndexPath:indexPath];
        LGVoiceLeftPlayState voiceLeftPlayState;
        switch (audioPlayerState) {
            case LGAudioPlayerStateNormal:
                voiceLeftPlayState = LGVoicePlayLeftStateNormal;
                break;
            case LGAudioPlayerStatePlaying:
                voiceLeftPlayState = LGVoicePlayLeftStatePlaying;
                break;
            case LGAudioPlayerStateCancel:
                voiceLeftPlayState = LGVoicePlayLeftStateCancel;
                break;
            default:
                break;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [voiceLeftMessageCell setVoiceLeftPlayState:voiceLeftPlayState];
        });
    }
}

#pragma mark -- 点击查看大图
-(void)didSelecteImageBrowserWithIndex:(NSInteger)index imageView:(UIImageView *)imageView {
    NSMutableArray <YBImageBrowseCellData *>* imageSource = [NSMutableArray array];
    NSMutableArray *imageArray = [NSMutableArray array];

    __block NSInteger currentIndex = 0;
    for (RCMessage * msg in self.chatRoomDataArray) {
        if ([(RCImageMessage *)msg.content isMemberOfClass:[RCImageMessage class]]) {
            RCImageMessage * imageMsg = (RCImageMessage *)msg.content;
            [imageArray addObject:imageMsg];
        }else if ([(RCSightMessage *)msg.content isMemberOfClass:[RCSightMessage class]]) {
            RCSightMessage * sightMsg = (RCSightMessage *)msg.content;
            [imageArray addObject:sightMsg];
        }
    }
    if (imageArray.count==0) return;
    [imageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RCImageMessage *imageMsg = (RCImageMessage *)obj;
        RCSightMessage *sightMsg = (RCSightMessage *)obj;
        if ([imageMsg isMemberOfClass:[RCImageMessage class]]) {
            YBImageBrowseCellData *ImageData = [YBImageBrowseCellData new];
            ImageData.url = [NSURL URLWithString:imageMsg.imageUrl];
            ImageData.sourceObject = imageView;
            [imageSource addObject:ImageData];
            /// 判断当前 Index
            RCImageMessage *tapImageMessage = (RCImageMessage *)self.chatRoomDataArray[index].content;
            if ([obj isEqual:tapImageMessage]) {
                currentIndex = idx;
            }
        }else if ([sightMsg isMemberOfClass:[RCSightMessage class]]) {
            LKLog(@"视频播放查看");
        }
    }];
    YBImageBrowser * imageBrowser =[YBImageBrowser new];
    [imageBrowser.defaultToolBar hideOperationButton];
    imageBrowser.dataSourceArray = imageSource;
    imageBrowser.currentIndex = currentIndex;
    [imageBrowser show];
}


#pragma mark -- 底部聊天输入框视图
#pragma mark -- 礼物视图
-(HJGiftScrollView *)giftScrollView {
    if (!_giftScrollView) {
        UIButton * didBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        didBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGTH-350);
        didBtn.tag = 1010101;
        [didBtn addTarget:self action:@selector(didHidenGitView) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:didBtn];
        [self.view bringSubviewToFront:didBtn];
        
        _giftScrollView = [[HJGiftScrollView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGTH, SCREEN_WIDTH, 350)];
        [[UIApplication sharedApplication].keyWindow addSubview:_giftScrollView];
    }
    return _giftScrollView;
}
-(void)didHidenGitView {
    [self sendGiftClicked];
}
-(void)sendGiftClicked {
    UIButton * btn = [self.view viewWithTag:1010101];
    [btn removeFromSuperview];
    WS(weakSelf)
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.giftScrollView.frame = CGRectMake(0, SCREEN_HEIGTH, SCREEN_WIDTH, 350);
    } completion:^(BOOL finished) {
        [weakSelf.giftScrollView removeFromSuperview];
        weakSelf.giftScrollView = nil;
    }];
}
#pragma mark --textViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
    self.chageBtn.selected = YES;
    [self ChangeBtnClicked:self.chageBtn];
}
-(void)textViewDidEndEditing:(UITextView *)textView {
    NSRange rang = NSMakeRange(0, textView.text.length);
    WS(weakSelf)
    if ([textView.text isEqualToString:@""] && rang.length == 0) {
        [self.senBtn setHidden:YES];
        [self.chageBtn setHidden:NO];
        [UIView performWithoutAnimation:^{
            weakSelf.btmView_h.constant = 60;
        }];
        return;
    }
}

-(void)textViewDidChange:(UITextView *)textView {
    [self.senBtn setHidden:NO];
    [self.chageBtn setHidden:YES];
    CGRect frame = textView.frame;
    CGSize size = [textView sizeThatFits:CGSizeMake(frame.size.width, CGFLOAT_MAX)];
    if (size.height > 100) {
        self.inputTextView.scrollEnabled = YES;
        return;
    }
    WS(weakSelf)
    if (size.height < 40) {
        size.height = 40;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView performWithoutAnimation:^{
            weakSelf.btmView_h.constant = size.height+20;
        }];
    });
    
}


- (IBAction)vocieBtnClicked:(UIButton *)sender {
    [self.view endEditing:YES];
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.inputTextView setHidden:YES];
        [self.vocieNumBtn setHidden:NO];
        return;
    }
    [self.inputTextView setHidden:NO];
    [self.vocieNumBtn setHidden:YES];
}

#pragma mark -- 加载gif图
-(HJGifImageView *)gifImageView {
    if (!_gifImageView) {
        self.gifBackView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2 - 49.5, 104, 99, 104)];
        self.gifBackView.backgroundColor = [UIColor blackColor];
        self.gifBackView.alpha = 0.6;
        [self.gifBackView rounded:UIRectCornerAllCorners radius:6];
        [self.view addSubview:self.gifBackView];
        [self.view bringSubviewToFront:self.gifBackView];
        
        NSString * path = [[NSBundle mainBundle] pathForResource:@"语音动图" ofType:@"gif"];
        _gifImageView = [[HJGifImageView alloc] initWithGIFPath:path];
        _gifImageView.frame = CGRectMake(self.gifBackView.left, 104, 99, 104);
        [self.view addSubview:_gifImageView];
        [self.view bringSubviewToFront:_gifImageView];
    }
    return _gifImageView;
}
#pragma mark -- 录音

//按住说话
- (IBAction)vocieBtnTouchDown:(UIButton *)sender {
    if (![self canRecord]) {
        [self showErrorHUDWithError:@"请启用麦克风-设置/隐私/麦克风"];return;
    }
    [[HJVociePlayer shareManager] stopAudioPlayer];
    [self startRecord];
    [self.gifImageView startGIF];
}
//上滑离开按钮区域松开 取消
- (IBAction)vocieBtnTouchUpOutSide:(UIButton *)sender {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self hidenGifView];
        [self.cancelVocieImageView removeFromSuperview];
        self.cancelVocieImageView = nil;
    });
    [self cancelVioceRecord];
}
// 松开手指，取消发送
- (IBAction)vocieTouchDragExit:(UIButton *)sender {
    [self hidenGifView];
    [self.view addSubview:self.cancelVocieImageView];
    [self.view bringSubviewToFront:self.cancelVocieImageView];
    [self cancelVioceRecord];
}
// 手指上滑，取消发送
- (IBAction)vocieBtnTouchDragEnter:(UIButton *)sender {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self hidenGifView];
        [self.cancelVocieImageView removeFromSuperview];
        self.cancelVocieImageView = nil;
    });
    [self cancelVioceRecord];
}

//按住说话
- (IBAction)voiceNumBtnClicked:(UIButton *)sender {
    if (self.countDown<1) return;
    [self sendRecord];
}

-(UIImageView *)cancelVocieImageView {
    if (!_cancelVocieImageView) {
        UIImageView * imageView = [[UIImageView alloc] initWithImage:setImage(@"recordCancle")];
        imageView.frame = CGRectMake(SCREEN_WIDTH/2-(imageView.image.size.width /2), imageView.image.size.height, imageView.image.size.width, imageView.image.size.height);
        _cancelVocieImageView = imageView;
    }
    return _cancelVocieImageView;
}

/**
 隐藏gif动画图
 */
-(void)hidenGifView {
    [self.gifImageView stopGIF];
    [self.gifBackView removeFromSuperview];
    [self.gifImageView removeFromSuperview];
    self.gifBackView = nil;
    self.gifImageView = nil;
}

// 发送消息
- (IBAction)senMsgBtnClicked:(UIButton *)sender {
    NSString * text = self.inputTextView.text;
    NSString *temp = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//清空空格
    if([text isEqualToString:@""] || temp.length==0) {
        [self showErrorHUDWithError:@"发送的内容不能为空"];
        return;
    }
    HJUserModel * userModel = [HJUserManager getUserModel];
    RCTextMessage *testMessage = [RCTextMessage messageWithContent:text];
    RCUserInfo * currentInfo = [[RCUserInfo alloc]initWithUserId:userModel.userId name:userModel.nickName portrait:userModel.avatar];
    testMessage.senderUserInfo = currentInfo;
    RCMessage * rcMsg = [[RCIMClient sharedRCIMClient] sendMessage:ConversationType_PRIVATE targetId:self.conversationModel.targetId content:testMessage pushContent:self.inputTextView.text pushData:nil success:^(long messageId) {
        NSLog(@"发送成功。当前消息ID：%ld", messageId);
    } error:^(RCErrorCode nErrorCode, long messageId) {
        NSLog(@"发送失败。消息ID：%ld， 错误码：%ld", messageId, (long)nErrorCode);
    }];
    if (!rcMsg) return;
    [self.chatRoomDataArray addObject:rcMsg];
    [self.tableView reloadData];
    [self tableViewScroll];
    WS(weakSelf)
    [UIView performWithoutAnimation:^{
        weakSelf.btmView_h.constant = 60.0;
        weakSelf.inputTextView.text = @"";
    }];
    
    [self localLastMessage:testMessage];
}

- (IBAction)ChangeBtnClicked:(UIButton *)sender {
//    WS(weakSelf)
    sender.selected = !sender.selected;
    self.chageBtn.selected = sender.selected;
    if (sender.selected) {
        [self.btmCategoryView setHidden:NO];
        if ([self.inputTextView isFirstResponder]) {
            [self.inputTextView resignFirstResponder];
        }
        self.btmView_h.constant = 142;
        self.btmCategoryView_H.constant = 82;
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height) animated:NO];
    }else {
        [self.btmCategoryView setHidden:YES];
        self.btmView_h.constant = 60.0;
        self.btmCategoryView_H.constant = 0.0;
    }
}

// tag 111  112  113  114
- (IBAction)btmCategeryBtnClicked:(UIButton *)sender {
    WS(weakSelf)
//    self.chageBtn.selected = YES;
    [self ChangeBtnClicked:self.chageBtn];
    switch (sender.tag) {
        case 111: // 图片
        {
            if ([TZImagePickerTool checkPhotoPermisson]) {
                [TZImagePickerTool selectImageFrom:self complete:^(UIImage *img) {
                    HJUserModel * userModel = [HJUserManager getUserModel];
                    RCUserInfo * currentInfo = [[RCUserInfo alloc]initWithUserId:userModel.userId name:userModel.nickName portrait:userModel.avatar];
                    RCImageMessage * imageMessage = [RCImageMessage messageWithImage:img];
                    imageMessage.senderUserInfo = currentInfo;
                    [weakSelf sendToImage:imageMessage];
                } isCamera:NO];
            }
        }
            break;
        case 112: // 拍摄
        {
            YFCamera * camera = [YFCamera camera];
            camera.isTakePhoto = YES;
            [camera completedWithImage:^(UIImage * _Nullable image) {
                HJUserModel * userModel = [HJUserManager getUserModel];
                RCUserInfo * currentInfo = [[RCUserInfo alloc]initWithUserId:userModel.userId name:userModel.nickName portrait:userModel.avatar];
                RCImageMessage * imageMessage = [RCImageMessage messageWithImage:image];
                imageMessage.senderUserInfo = currentInfo;
                [weakSelf sendToImage:imageMessage];
            } withVideo:^(UIImage * _Nullable firstFrameImage, NSURL * _Nullable videoURL, long long duration) {
                RCSightMessage * sightMsg = [RCSightMessage messageWithLocalPath:videoURL.path thumbnail:firstFrameImage duration:duration];
                NSString * pushContent = @"发来一段视频";
                [[RCIMClient sharedRCIMClient] sendMediaMessage:ConversationType_PRIVATE targetId:weakSelf.conversationModel.targetId content:sightMsg pushContent:pushContent pushData:nil uploadPrepare:^(RCUploadMediaStatusListener *uploadListener) {
                } progress:^(int progress, long messageId) {
                    NSLog(@"进度==%d",progress);
                } success:^(long messageId) {
                    NSLog(@"发送视频成功。当前消息ID：%ld", messageId);
                } error:^(RCErrorCode errorCode, long messageId) {
                    NSLog(@"发送视频失败。消息ID：%ld， 错误码：%ld", messageId, (long)errorCode);
                } cancel:nil];
            }];
            [camera show];
        }
            break;
        case 113:
        {
            [UIView animateWithDuration:0.5 animations:^{
                self.giftScrollView.frame = CGRectMake(0, SCREEN_HEIGTH-350, SCREEN_WIDTH, 350);
            } completion:nil];
        }
            break;
        case 114:
        {
            if ([self.journeyModel isEqual:[NSNull null]]) {
                [self showErrorHUDWithError:@"请发布行程"];
                return;
            }
            [self pushToTeamViewControllerWithUIType:UIContentTypeNormal index:nil];
        }
            break;
        default:
            break;
    }
}

/**
 跳转至组队界面
 @param type UI类型枚举
 */
-(void)pushToTeamViewControllerWithUIType:(contentType)type index:(NSIndexPath *)index {
    HJTeamVC * teamVC = [HJTeamVC new];
    teamVC.UIType = type;
    teamVC.isChat = YES;
    if (index) {
        HJSimpleMessage * simpleMsg = (HJSimpleMessage *)self.chatRoomDataArray[index.row].content;
        HJSimpleModel * simpModel = [HJSimpleModel yy_modelWithDictionary:simpleMsg.content];
        teamVC.simpleModel = simpModel;
    }
    teamVC.journeyModel = self.journeyModel;
    teamVC.otherModel = self.otherModel;
    [self.navigationController pushViewController:teamVC animated:YES];
}

#pragma mark -- 发送图片消息
-(void)sendToImage:(RCImageMessage *)imageMsg {
   
    RCMessage * rcMsg = [[RCIMClient sharedRCIMClient] sendMediaMessage:ConversationType_PRIVATE targetId:self.conversationModel.targetId content:imageMsg pushContent:nil pushData:nil progress:^(int progress, long messageId) {
        NSLog(@"进度==%d",progress);
    } success:^(long messageId) {
        NSLog(@"发送成功。当前消息ID：%ld", messageId);
    } error:^(RCErrorCode errorCode, long messageId) {
        NSLog(@"发送失败。消息ID：%ld， 错误码：%ld", messageId, (long)errorCode);
    } cancel:nil];
    [self.chatRoomDataArray addObject:rcMsg];
    [self.tableView reloadData];
    [self tableViewScroll];
    
    [self localLastMessage:imageMsg];
    
}


#pragma mark --  启动录音器
- (void)startRecord {
    self.countDown = 60;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    //设置AVAudioSession
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];
    //设置录音输入源
    UInt32 doChangeDefaultRoute = 1;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &doChangeDefaultRoute);
    [audioSession setActive:YES error:&err];
    if (audioSession == nil) {
        NSLog(@"Error creating session: %@",[err description]);
        return;
    } else {
        [audioSession setActive:YES error:nil];
    }
    //获取文件沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //设置文件保存路径和名称
    NSString *fileName = [NSString stringWithFormat:@"/VoiceMsgRecord%5.2f.wav", [[NSDate date] timeIntervalSince1970]];
    self.recordFilePath = [path stringByAppendingPathComponent:fileName];
    
    NSURL *recordedFile = [NSURL fileURLWithPath:self.recordFilePath];
    //设置参数
    NSDictionary *recordSetting = @{AVFormatIDKey: @(kAudioFormatLinearPCM),
                                    AVSampleRateKey: @8000.00f,
                                    AVNumberOfChannelsKey: @1,
                                    AVLinearPCMBitDepthKey: @16,
                                    AVLinearPCMIsNonInterleaved: @NO,
                                    AVLinearPCMIsFloatKey: @NO,
                                    AVLinearPCMIsBigEndianKey: @NO};
    //初始化AVAudioRecorder
    err = nil;
    AVAudioRecorder * recorder = [[AVAudioRecorder alloc] initWithURL:recordedFile settings:recordSetting error:&err];
    self.recorder = recorder;
    if(recorder == nil) return;
    //准备和开始录音
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;
    [recorder record];
    [recorder recordForDuration:0];
    if (self.recordTimer) {
        [self.recordTimer invalidate];
        self.recordTimer = nil;
    }
    self.recordTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector:@selector(levelTimerCallback) userInfo: nil repeats: YES];
    [[NSRunLoop currentRunLoop] addTimer:self.recordTimer forMode:NSRunLoopCommonModes];
}

/**
 录音定时器
 */
-(void)levelTimerCallback{
    [self.recorder updateMeters];
    _countDown--;
    LKLog(@"_countDown=%zd",_countDown);
    //超时自动发送
    if (_countDown < 1) {
        [self sendRecord];
    }
}

/**
 取消录音
 */
-(void)cancelVioceRecord {
    [self hidenGifView];
    //停止录音 移除定时器
    [self.recordTimer invalidate];
    self.recordTimer = nil;
    [self.recorder stop];
}
//松开发送
-(void)sendRecord {
    [self hidenGifView];
    //停止录音 移除定时器
    [self.recordTimer invalidate];
    self.recordTimer = nil;
    if ([self.recorder isRecording]) {
        [self.recorder stop];
    }
    if (_countDown >= 59) {
        [YFHud showError:@"说话时间太短!"];
        return;
    }
    NSData * vocieData = [NSData dataWithContentsOfFile:_recordFilePath];
    AVURLAsset*audioAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:_recordFilePath isDirectory:NO] options:nil];
    CMTime audioDuration = audioAsset.duration;
    long audioDurationSeconds = CMTimeGetSeconds(audioDuration);
    if (audioDurationSeconds==0 || !vocieData) return;
    RCVoiceMessage * vocieMsg = [RCVoiceMessage messageWithAudio:vocieData duration:audioDurationSeconds];
    RCMessage * rcMsg = [[RCIMClient sharedRCIMClient] sendMessage:ConversationType_PRIVATE targetId:self.conversationModel.targetId content:vocieMsg pushContent:@"语音" pushData:nil success:^(long messageId) {
        NSLog(@"发送语音消息成功");
    } error:^(RCErrorCode nErrorCode, long messageId) {
        NSLog(@"发送语音消息失败，错误码是 (%ld)", (long)nErrorCode);
    }];
    [self.chatRoomDataArray addObject:rcMsg];
    [self.tableView reloadData];
    [self tableViewScroll];
    
    [self localLastMessage:vocieMsg];
}
//检查是否拥有麦克风权限
- (BOOL)canRecord {
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
        [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
            if (granted) {
                bCanRecord = YES;
            } else {
                bCanRecord = NO;
            }
        }];
    }
    return bCanRecord;
}
@end

